package com.chatplus.application.controller.api.extend;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.chatplus.application.common.constant.RedisPrefix;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.extend.ZaoBaoNewsDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.codec.SerializationCodec;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

/**
 * 今日早报新闻
 */
@Validated
@RestController
@RequestMapping("/api/extend/")
@Tag(name = "微博第三方API", description = "微博第三方API")
public class ZaoBaoNewsExtendController {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ZaoBaoNewsExtendController.class);

    private final RedissonClient redissonClient;
    private final ObjectMapper objectMapper;

    public ZaoBaoNewsExtendController(RedissonClient redissonClient, ObjectMapper objectMapper) {
        this.redissonClient = redissonClient;
        this.objectMapper = objectMapper;
    }

    @GetMapping("/zaoBaoNews")
    @Operation(summary = "获取今日早报")
    public ZaoBaoNewsDto zaoBaoNews() {
        String redisKey = RedisPrefix.EXTEND_REDIS_PREFIX_TEST + "zaoBaoNews";
        RBucket<ZaoBaoNewsDto> rBucket = redissonClient.getBucket(redisKey, new SerializationCodec());
        ZaoBaoNewsDto cache = rBucket.isExists() ? rBucket.get() : null;
        if (cache != null) {
            return cache;
        }
        LOGGER.message("获取今日早报").info();
        String url = "https://api.suxun.site/api/sixs?type=json";
        try (HttpResponse response = HttpUtil.createGet(url).execute()) {
            String dataText = response.body();
            cache = objectMapper.readValue(dataText, ZaoBaoNewsDto.class);
            rBucket.set(cache, Duration.ofMinutes(30));
        } catch (Exception e) {
            LOGGER.message("获取今日早报失败").exception(e).error();
        }
        return cache;
    }
}
